<?
function ldapList($conn) {
	echo "<table cellspacing=\"0\" style=\"width: 600px\">";

	if(  ! isset($_GET['t']) OR ($_GET['t']=='users') ) {
		$info = getLdapUsers($conn);
		$count = count($info);

		echo "<tr><td colspan=4 class=\"tbhead\">".$count." användare</td></tr>\n";
		for ($i=0; $i<$count; $i++) {
                        $displayname="";
                        if(isset($info[$i]["displayname"][0]))
                            $displayname=utf8_decode($info[$i]["displayname"][0]);

			echo "<tr ".($i%2==1?"class='list1'":"class='list2'").'><td>'."\n";
			echo ' <input type="checkbox" name="usermany'.$info[$i]['uidnumber'][0].'"></td><td onClick="location = \'?s=ldap&t=users&u='.$info[$i]["cn"][0].'\'" '.help('list_user_show').'>';
			echo "  <a href=\"?s=ldap&t=users&u=".$info[$i]["cn"][0]."\">".$info[$i]["cn"][0]."</a>\n";
			echo '</td><td style="font-style: italic;" onClick="location = \'?s=ldap&t=users&u='.$info[$i]["cn"][0].'\'" '.help('list_user_show').'>'."\n";
			echo "  <a href=\"?s=ldap&t=users&u=".$info[$i]["cn"][0]."\">".$displayname."</a>\n";
			echo ($info[$i]["uidnumber"][0]!=0?"</td><td style='width: 8px' ".help('list_user_del').">\n
			<a href=?s=ldap&t=users&del=user&name=".$info[$i]["cn"][0]."&do=1 ".confirm('del_user')."><img src=/images/delete.png border=0></a>\n":"</td><td>");
			echo "</td></tr>\n";
		}
			 	
		echo "<tr><td colspan=4 >Med valda användare: <input type=\"hidden\" name=\"b_modmany\" value=\"FALSE\" id=\"b_modmany\"><a href=\"javascript:document.getElementById('b_modmany').value = 'TRUE'; document.pageform.submit(); \"><img src=\"images/edithand.png\"/></a> <input type=\"hidden\" name=\"b_delmany\" value=\"FALSE\" id=\"b_delmany\"><a href=\"javascript:document.getElementById('b_delmany').value = 'TRUE'; document.pageform.submit();\" ".confirm("del_manyusers")."><img src=\"images/delete.png\"/></a> </td></tr>";
		echo "</table><br>\n";
		
		echo "<table  cellspacing=\"0\" style=\"border: 1px solid #bbb; width: 20em; padding: 0.5em;\" ".help('list_user_new').">";
		echo "<tr><td colspan=3><b>Skapa ny</b></td>\n";
		echo "<td rowspan=4 style=\"text-align: right; vertical-align: bottom;\"><input type=\"submit\" name=\"b_add\" value=\"skapa\" class=\"button\" /></td></tr>";
		echo "<tr><td>användarnamn:</td><td colspan=2 style=\"text-align: left;\"><input class=\"input-box\" type=\"text\" name=\"name\" style=\"width: 8em\"></td></tr>\n";
		echo "<tr><td>lösenord:</td><td colspan=2 style=\"text-align: left;\"><input class=\"input-box\" type=\"password\" name=\"pass1\" style=\"width: 8em\"></td></tr>\n";
		echo "<tr><td>lösenord igen:</td><td colspan=2 style=\"text-align: left;\"><input class=\"input-box\" type=\"password\" name=\"pass2\" style=\"width: 8em\"></td></tr>\n";
		echo "</table>";
	}

	if( isset($_GET['t']) && ($_GET['t']=='groups') ) {
		$info = getLdapGroups($conn);
		$count = count($info);
		echo "<tr><td colspan=3 class=\"tbhead\">".$count." grupper</td></tr>\n";
		for ($i=0; $i<$count; $i++) {
			echo "<tr ".($i%2==1?"class='list1'":"class='list2'").'><td onClick="location = \'?s=ldap&t=groups&g='.$info[$i]["cn"][0].'\'" '.help('list_group_show').'>'."\n";
			echo "  <a href=\"?s=ldap&t=groups&g=".$info[$i]["cn"][0]."\">".$info[$i]["cn"][0]."</a>\n";
			echo '</td><td style="font-style: italic;" onClick="location = \'?s=ldap&t=groups&g='.$info[$i]["cn"][0].'\'" '.help('list_group_show').'>'."\n";
			echo "  <a href=\"?s=ldap&t=groups&g=".$info[$i]["cn"][0]."\">".utf8_decode($info[$i]["description"][0])."</a>\n";
			echo "</td><td style='width: 8px' ".help('list_group_del').">\n";
			echo "  <a href=\"?s=ldap&t=groups&del=group&name=".$info[$i]["cn"][0]."&do=1 \" ".confirm('del_group')."><img src=/images/delete.png border=0></a>\n";
			echo "</td></tr>\n";
		}
		echo "</table><br>\n";
		echo "<table  cellspacing=\"0\" style=\"border: 1px solid #bbb; width: 20em; padding: 0.5em;\" ".help('list_user_new').">";
		echo "<tr><td colspan=3><b>Skapa ny</b></td>\n";
		echo "<td rowspan=3 style=\"text-align: right; vertical-align: bottom;\"><input type=\"submit\" name=\"b_add\" value=\"skapa\" class=\"button\" /></td></tr>";
		echo "<tr><td>gruppnamn:</td><td colspan=2 style=\"text-align: left;\"><input class=\"input-box\" type=\"text\" name=\"name\" style=\"width: 8em\"></td></tr>\n";
		echo "</table>";
	}

	echo "<br>\n";
};

function ldapUser($conn, $name) {
	echo "<table><tr><td>";
	event($conn,"usershow");
	
	echo "</td></tr></table>";
	echo "<input type=\"hidden\" name=\"name\" value=\"$name\">";
};

function ldapUserMany($conn, $userstring) {
	echo "<table><tr><td>";
	event($conn,"usershowmany");
	
	echo "</td></tr></table>";
};

function ldapGroup($conn, $name) {
	$sr=ldap_search($conn, $GLOBALS["dc"], "(&(objectclass=posixGroup)(cn=$name))"); 
	$info = ldap_get_entries($conn, $sr);
	echo "<table class=framed>";
	echo "<tr><td class=tbhead colspan=2>Grupphantering</td></tr>";
	echo "<tr><td>gruppnamn:</td><td>".$info[0]["cn"][0]."</td></tr>";
	echo "<tr><td>beskrivning:</td><td><input class=\"input-box\" type=\"text\" size=30 name=\"description\" value=\"".utf8_decode($info[0]["description"][0])."\"></td></tr>";

	echo "</table>";
	echo "<input type=hidden name=cn value=\"$name\">";
	echo "<table class=framed>";
	echo "<tr><td class=tbhead>Användare i gruppen</td></tr>";
	echo "<tr><td>";
	echo "<table>";
        //Om det finns några medlemmar i gruppen ska de listas
        if( isset($info[0]["memberuid"]) ) {
            $count = count($info[0]["memberuid"]) -1;
            for ($i=0; $i < $count; $i++) {
                    echo "<tr><td><a href=\"?s=ldap&u=".$info[0]["memberuid"][$i]."\">";
                    echo $info[0]["memberuid"][$i]."</a></td>";
                    echo "<td><a href=\"?s=ldap&g=".$info[0]["cn"][0]."&t=groups&mod=user&name=".$info[0]["memberuid"][$i]."&delGroup=".$info[0]["cn"][0]."&do=1\"><img src=/images/delete.png border=\"0\" ".help('group_del_user')." ".confirm('remove_user_from_group')."></a></td></tr>";
            };
        }
	echo "</table>";
	
	echo "</td></tr></table>";
};


function importForm($conn) {
        if (isset($_GET['action'])) {
            if ($_GET['action']=='usermany') {
                    $userstring = $_GET['userstring'];
                    ldapUserMany($conn,$userstring);
            } elseif (isset($_GET['action']) AND ($_GET['action']=='confirm')) {
                    $button = '<input type="submit" name="b_usermodmany" value="Hantera användare" class="buttonlong" />';

                    echo '
                            <table style="width:30em">
                            <tr><td class="tbhead" colspan="3">Användarlista</td></tr>
                            <tr style="font-weight:bold"><td>Användarnamn</td><td>Fullständigt namn</td><td>Lösenord</td></tr>
                    ';
                    for($i=0;$i<count($_SESSION['import']['user']);$i++) {
                                    echo '<tr>';
                                    echo '<td>'.$_SESSION['import']['user'][$i]['name'].'</td>';
                                    echo '<td>'.$_SESSION['import']['user'][$i]['fullname'].'</td>';
                                    echo '<td>'.$_SESSION['import']['user'][$i]['password'].'</td></tr>';

                    }
                    echo '
                            <input type="hidden" name="action" value="confirm">
                            <tr><td colspan="3" class="tbfoot">Skriv ut sidan, eller <a href="getf.php?s=ldap&f=users.csv" target="_blank" style="color:blue; text-decoration:underline">hämta CSV-lista</a></td></tr>
                            <tr><td colspan="3" style="padding-top:1em;">'.$button.'</td></tr>
                            </table>
                            <br>
                    ';

            } elseif (isset($_GET['action']) AND ($_GET['action']=='check')) {
                    if (isset($_GET['error']) AND $_GET['error'] )  {
                            $button = '<input type="submit" name="back" value="backa" class="button" />';
                    } else {
                            $button = '<input type="submit" name="b_import" value="godkänn" class="button" />';
                            echo '<input type="hidden" name="action" value="confirm">';
                    }

                    echo '
                            <table>
                                    <tr><td class="tbhead" colspan="2">Kontrollera användare</td></tr>
                                    <tr><td><b>Användarnamn&nbsp;&nbsp;&nbsp;</b></td><td><b>Fullständigt namn</b></td></tr>
                                    '.$_SESSION['import']['formatted'].'
                                    <tr><td>'.$button.'</td><td>&nbsp;</td></tr>
                            </table>
                    ';
            }
        } else {

		echo 'Skriv eller kopiera in en lista på användarnamn så att varje användare står på en egen rad.<br>';

                echo '<table><tr><td>';
		echo '<b>Så här:</b><br><div style="width:20em;border:1px solid black">andjoh<br>stieri<br></div><br>';
                echo '</td><td>';
                echo '<b>eller så här:</b><br><div style="width:20em;border:1px solid black">andjoh, Anders Johansson<br>stieri, Stig Eriksson<br></div><br>';
                echo '</td></tr></table>';
		echo '
			<table>
				<tr><td class="tbhead">Importera Användare</td></tr>
				<tr><td><textarea name="importcsv" style="width:30em; height:20em;">';
		if( isset($_SESSION['import']['users']) && !isset($_SESSION['import']['done']) ) {
                        foreach( $_SESSION['import']['users'] AS $i=>$user) {
                                $fname = $_SESSION['import']['fullnames'][$i];
                                echo $user.", \"".$fname."\"\n";
			}
		}
		echo '</textarea></td></tr>
				<input type="hidden" name="action" value="check">
				<tr><td><input type="submit" name="b_import" value="importera" class="button" /></td></tr>


			</table>
		';
	}

}

//////////////////////////////////////////
//////////////////////////////////////////


	$conn = ldapConnect();
	if (isset($_GET["u"]) AND $_GET["u"] ) {
		html_start( array( array( 'users', 'Användare') ));
		ldapUser($conn,$_GET["u"]);
		html_end(true, true, true, 'ldap', 'users');
	} elseif (isset($_GET["users"]) AND $_GET["users"]) {
		html_start( array( array( 'users', 'Användare') ));
		ldapUserMany($conn,$_GET['users']);
		html_end(true, true, true, 'ldap', 'users');
	} elseif (isset($_GET["g"]) AND $_GET["g"]) {
		html_start( array( array( 'groups', 'Grupp') ));
		ldapGroup($conn, unhtmlspecialchars($_GET["g"]));
		html_end(true, true, true, 'ldap', 'groups');
	} elseif (isset($_GET["t"]) && ($_GET["t"]=='import')) {
		html_start( array(
			array( 'users', 'Användare'),
			array( 'groups', 'Grupper'),
			array( 'import', 'Importera')
		) );
		importForm($conn);
		html_end();
	} else {
		html_start( array(
			array( 'users', 'Användare'),
			array( 'groups', 'Grupper'),
			array( 'import', 'Importera')
		) );
		ldapList($conn);
		html_end();
	};
	ldap_close($conn);
?>
